import axios from 'axios';
import router from "../../router";

axios.defaults.timeout = 50000;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = 'http://127.0.0.1:8081/api';

axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response)
    }
    return Promise.reject(response)
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // Not Found
        case 404:
          router.replace({
            path: '/',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break;
        case -10001:
          router.replace({
            path: '/',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break
      }
      return Promise.reject(error)
    }
  }
);

export function getData(url, params = {}) {
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params: params,
        headers: {
          'content-type': 'application/json',
          'token': localStorage.token
        }
      }).then(res => {
        resolve(res.data);
    }).catch(err =>{
      reject(err.data)
    })
  });
}

export function postData(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params, {
      headers: {
        'content-type': 'application/json',
        'token': localStorage.token
      }
    }).then(res => {
        resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

